package com.chensi.admin.userservice.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

/**
 * @author si.chen
 */
@Slf4j
public class AES {

    private static SecretKeySpec secretKey;
    private static byte[] key;
    private static String decryptedString;
    private static String encryptedString;
    private static int keyLength = 16;
    private static String charset = "UTF-8";
    private static String encryptionSHA = "SHA-1";
    private static String encryptionAES = "AES";

    public static void setKey(String myKey) {
        MessageDigest sha;
        try {
            key = myKey.getBytes(charset);
            sha = MessageDigest.getInstance(encryptionSHA);
            key = sha.digest(key);
            key = Arrays.copyOf(key, keyLength);
            secretKey = new SecretKeySpec(key, encryptionAES);
        } catch (NoSuchAlgorithmException e) {
            log.error(e.toString());
        } catch (UnsupportedEncodingException e) {
            log.error(e.toString());
        }
    }

    public static String getDecryptedString() {
        return decryptedString;
    }

    public static void setDecryptedString(String decryptedString) {
        AES.decryptedString = decryptedString;
    }

    public static String getEncryptedString() {
        return encryptedString;
    }

    public static void setEncryptedString(String encryptedString) {
        AES.encryptedString = encryptedString;
    }

    public static String encrypt(String strToEncrypt) {
        try {
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
            setEncryptedString(Base64.encodeBase64URLSafeString(cipher.doFinal(strToEncrypt.getBytes(charset))));
        } catch (Exception e) {
            log.error("Error while encrypting:" + e);
        }
        return null;
    }

    public static String decrypt(String strToDecrypt) {
        try {
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
            cipher.init(Cipher.DECRYPT_MODE, secretKey);
            setDecryptedString(new String(cipher.doFinal(Base64.decodeBase64(strToDecrypt))));
        } catch (Exception e) {
            log.error("Error while decrypting: " + e);
        }
        return null;
    }

}
